package com.amanda.reggie.service.impl;

import com.amanda.reggie.common.BaseContext;
import com.amanda.reggie.common.CustomException;
import com.amanda.reggie.common.R;
import com.amanda.reggie.dto.OrdersDto;
import com.amanda.reggie.entity.*;
import com.amanda.reggie.mapper.OrdersMapper;
import com.amanda.reggie.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author amanda
 * @Description 订单业务实现
 */
@Slf4j
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 订单查询
     */
    @Override
    @Transactional
    public Page<OrdersDto> pageQuery(int page, int pageSize, String number, String beginTime, String endTime) {
        // 1、分页构造器
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();
        // 2、条件过滤器
        LambdaQueryWrapper<Orders> ordersQueryWrapper = new LambdaQueryWrapper<>();
        // 3、过滤
        ordersQueryWrapper.like(number != null, Orders::getNumber, number);
        ordersQueryWrapper.gt(StringUtils.isNotEmpty(beginTime), Orders::getOrderTime, beginTime);
        ordersQueryWrapper.lt(StringUtils.isNotEmpty(endTime), Orders::getOrderTime, endTime);
        // 4、排序
        ordersQueryWrapper.orderByDesc(Orders::getOrderTime);
        // 5、查询
        ordersService.page(ordersPage, ordersQueryWrapper);
        // 6、对象拷贝
        BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");
        // 7、处理record字段
        List<Orders> records = ordersPage.getRecords();
        List<OrdersDto> list = records.stream().map((orders) -> {
            OrdersDto ordersDto = new OrdersDto();
            // 7.1 拷贝
            BeanUtils.copyProperties(orders, ordersDto);
            LambdaQueryWrapper<OrderDetail> orderDetailWrapper = new LambdaQueryWrapper<>();
            // 7.2 查询订单详细信息
            orderDetailWrapper.eq(OrderDetail::getOrderId, orders.getId());
            // 7.3 查询订单内容，orders_detail
            List<OrderDetail> orderDetails = orderDetailService.list(orderDetailWrapper);
            ordersDto.setOrderDetails(orderDetails);
            // 7.4 根据ordersId查询用户
            Long userId = orders.getUserId();
            User user = userService.getById(userId);
            ordersDto.setUserName(user.getName());
            ordersDto.setPhone(user.getPhone());
            // 7.5 获取地址信息
            Long addressBookId = orders.getAddressBookId();
            AddressBook addressBook = addressBookService.getById(addressBookId);
            ordersDto.setAddress(addressBook.getDetail());
            ordersDto.setConsignee(addressBook.getConsignee());
            // 返回
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(list);
        return ordersDtoPage;
    }

    /**
     *更改订单状态
     */
    @Override
    public R<String> updateOrderStatus(Map<String, String> orderMap) {
        // 1、获取订单id
        Long orderId = Long.valueOf(orderMap.get("id"));
        // 2、获取订单状态
        int status = Integer.parseInt(orderMap.get("status"));
        // 3、判断
        if (status != 3) {
            if (status == 4) {
                throw new CustomException("订单正在派送中，等待用户拿取..");
            }else if (status == 5) {
                // 根据前端返回的数据，5之后的status不需要管，这里逻辑不太对，但和前端一起应该合理
                throw new CustomException("订单已经完成，请刷新系统..");
            }else {
                throw new CustomException("订单已被取消，请刷新系统..");
            }
        }
        Orders orders = ordersService.getById(orderId);
        orders.setStatus(status);
        ordersService.updateById(orders);
        return R.success("订单状态修改成功！");
    }

    /**
     * 提交订单
     */
    @Override
    @Transactional
    public void submitOrders(Orders orders) {
        // 1、获取当前用户id
        Long userId = BaseContext.getCurrentId();
        // 2、查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> shoppingCartWrapper = new LambdaQueryWrapper<>();
        shoppingCartWrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(shoppingCartWrapper);
        if (null == shoppingCarts || shoppingCarts.size() == 0) {
            throw new CustomException("购物车为空，数据错误，不能下单！");
        }
        // 2.1 查询用户数据
        User user = userService.getById(userId);
        // 2.2 查询用户地址信息
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (null == addressBook) {
            throw new CustomException("用户地址信息有误，不能下单！");
        }
        long orderId = IdWorker.getId(); // MP自动生成订单id
        AtomicInteger amount = new AtomicInteger(0); // 总金额，原子性操作，在多线程情况下也能有较好的性能
        // 3、计算总金额，处理订单详细信息
        List<OrderDetail> orderDetailList = shoppingCarts.stream().map((shoppingCart) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setAmount(shoppingCart.getAmount());
            amount.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        orders.setPayMethod(1);
        orders.setNumber(String.valueOf(orderId));
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));
        orders.setUserId(userId);
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        // 4、向订单表插入数据，一条即可
        this.save(orders);
        // 5、向订单详细表插入数据，一条/多条
        orderDetailService.saveBatch(orderDetailList);
        // 5、清空购物车
        shoppingCartService.remove(shoppingCartWrapper);
    }

    /**
     * 移动端的分页查询
     */
    @Override
    @Transactional
    public Page<OrdersDto> pageQuery(int page, int pageSize) {
        // 1、构造分页构造器
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();
        // 2、构造条件构造器
        LambdaQueryWrapper<Orders> dishQueryWrapper = new LambdaQueryWrapper<>();
        // 3、过滤
        dishQueryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        // 4、排序
        dishQueryWrapper.orderByDesc(Orders::getOrderTime);
        // 5、查询
        ordersService.page(pageInfo, dishQueryWrapper);
        // 6、对象拷贝
        BeanUtils.copyProperties(pageInfo, ordersDtoPage, "records");
        // 7、处理records
        List<Orders> records = pageInfo.getRecords();
        List<OrdersDto> list = records.stream().map((orders) -> {
            OrdersDto ordersDto = new OrdersDto();
            // 拷贝
            BeanUtils.copyProperties(orders, ordersDto);
            Long ordersId = orders.getId(); // 分类id
            List<OrderDetail> orderDetails = orderDetailService.getByOrderId(ordersId); // 分类对象
            if (null != orderDetails) {
                ordersDto.setOrderDetails(orderDetails);
            }
            return ordersDto;
        }).collect(Collectors.toList());
        // 8、封装
        return ordersDtoPage.setRecords(list);
    }

    /**
     * 再来一单
     */
    @Override
    @Transactional
    public void againSubmit(Map<String, String> map) {
        // 1、获取订单id
        String id = map.get("id");
        long orderId = Long.parseLong(id);
        // 1.1 获取当前用户id
        Long currentId = BaseContext.getCurrentId();
        // 2、构造器
        LambdaQueryWrapper<OrderDetail> orderDetailWrapper = new LambdaQueryWrapper<>();
        orderDetailWrapper.eq(OrderDetail::getOrderId, orderId);
        // 3、获取订单美食数据
        List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailWrapper);
        // 4、清除当前购物车数据
        LambdaQueryWrapper<ShoppingCart> shoppingCartWrapper = new LambdaQueryWrapper<>();
        shoppingCartWrapper.eq(ShoppingCart::getUserId, currentId);
        shoppingCartService.remove(shoppingCartWrapper);
        // 5、将订单美食数据重新写入当前购物车
        List<ShoppingCart> list = orderDetailList.stream().map((orderDetail) -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            // 6、拷贝
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(currentId);
            // 7、获取数据，存储到购物车
            Long dishId = orderDetail.getDishId();
            Long setmealId = orderDetail.getSetmealId();
            String dishFlavor = orderDetail.getDishFlavor();
            if (null != dishId) {
                shoppingCart.setDishId(dishId);
                shoppingCart.setDishFlavor(dishFlavor);
            } else {
                shoppingCart.setSetmealId(setmealId);
            }
            // 8、其它数据
            shoppingCart.setName(orderDetail.getName());
            shoppingCart.setNumber(orderDetail.getNumber());
            shoppingCart.setAmount(orderDetail.getAmount());
            shoppingCart.setImage(orderDetail.getImage());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartService.saveBatch(list);
    }
}
